package com.bear.fastrepair

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.res.Resources
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.findNavController
import com.bear.fastrepair.base.BaseActivity
import com.bear.fastrepair.databinding.ActivityMainBinding
import com.bear.fastrepair.entity.WebSocketResponse
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModel
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModelFactory
import com.bear.fastrepair.mvvm.ui.employee.dialog.AppUpdateProgressDialog
import com.bear.fastrepair.mvvm.ui.employee.dialog.AppUpdateSelectDialog
import com.bear.fastrepair.service.NotificationService
import com.bear.fastrepair.utils.*
import com.blankj.utilcode.util.*
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

class MainActivity : BaseActivity<ActivityMainBinding>() {

    private lateinit var navController: NavController
    private lateinit var viewModel: EmployeeViewModel
    private var _binder: NotificationService.NotificationBinder? = null
    private var newOrderListener: ((String) -> Unit)? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()
    }

    private fun init() {
        StatusBarUtils.setNormal(this)
        viewModel = ViewModelProvider(
            this,
            EmployeeViewModelFactory()
        ).get(EmployeeViewModel::class.java)
        viewModel.updateApp()
        viewModel.updateApp.observe(this) {
            if (it.code != 0) {
                return@observe
            }
            val localVersion = BuildConfig.VERSION_CODE
            // 还与远程的版本对比会更严谨
            val apkDir = File("${externalCacheDir?.absolutePath}/apk")
            if (FileUtils.isFileExists(apkDir)) {
                apkDir.listFiles()?.let { files ->
                    if (files.isNotEmpty()) {
                        files.filter { file -> file.name.contains(".apk") }.forEach { apk ->
                            val apkInfo = AppUtils.getApkInfo(apk)
                            val versionCode = apkInfo?.versionCode ?: 0
                            val versionName = apkInfo?.versionName ?: ""
                            Log.i(
                                "bear_repair",
                                "init: apk versionCode: $versionCode, remote versionCode:${it.data.versionCode}, local versionCode:${localVersion}"
                            )
                            // 本地已下载安装包，对比与服务器中的版本，版本号较小不做安装
                            if (versionCode <= localVersion || versionCode < it.data.versionCode) {
                                Log.i("bear_repair", "init: apk version is more lower")
                                return@forEach
                            }
                            AppUpdateSelectDialog(this, versionName) { _ ->
                                AppUtils.installApp(apk)
                            }.show()
                            return@observe
                        }
                    }
                }
                FileUtils.deleteAllInDir(apkDir)
            }
            if (localVersion >= it.data.versionCode) {
                Log.i("bear_repair", "init: local version is highest")
                return@observe
            }
            AppUpdateSelectDialog(
                this,
                versionName = it.data.versionName ?: "",
                description = it.data.description,
                createTime = it.data.createTime
            ) { _ ->
                AppUpdateProgressDialog(this, it.data, viewModel, this).show()
            }.show()
            LogUtils.i("local: $localVersion remote: ${it.data.versionCode}")
        }
        lifecycleScope.launch {
            val flag = SharedPreferencesHelper.getInt(PERMISSION_REQUEST_FLAG_KEY)
            if (flag == -1) {
                XXPermissions.with(this@MainActivity).permission(
                    listOf(
                        Permission.ACCESS_COARSE_LOCATION,
                        Permission.READ_PHONE_STATE,
                        Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.CALL_PHONE,
                        Permission.NOTIFICATION_SERVICE,
//                        Permission.ACCESS_BACKGROUND_LOCATION,
                        Permission.ACCESS_FINE_LOCATION,
//                        Permission.REQUEST_INSTALL_PACKAGES
                    )
                ).request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>?, all: Boolean) {
//                        if (all) ToastUtils.showLong("所有权限授予成功，可以正常使用本应用")
                        SharedPreferencesHelper.putInfo(
                            PERMISSION_REQUEST_FLAG_KEY,
                            PERMISSION_REQUESTED
                        )
                        XXPermissions.with(this@MainActivity)
                            .permission(Permission.ACCESS_BACKGROUND_LOCATION)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(
                                    permissions: MutableList<String>?,
                                    all: Boolean
                                ) {
                                    ToastUtils.showLong("恭喜，权限授予成功")
                                }

                                override fun onDenied(
                                    permissions: MutableList<String>?,
                                    never: Boolean
                                ) {
                                    super.onDenied(permissions, never)
                                    ToastUtils.showLong("请点击始终允许定位权限，用于正常派单操作")
//                                    XXPermissions.startPermissionActivity(this@MainActivity)
                                }
                            })
                    }

                    override fun onDenied(permissions: MutableList<String>?, never: Boolean) {
                        super.onDenied(permissions, never)
                        if (never) {
                            ToastUtils.showLong("发现有权限被永久拒绝，将影响应用正常使用！请打开权限")
//                            XXPermissions.startPermissionActivity(this@MainActivity)
                        } else {
                            ToastUtils.showLong("部分权限获取失败，请打开所有权限")
                        }
                    }
                })
            }
        }
        navController = findNavController(R.id.nav_host_fragment_container)
        navController.addOnDestinationChangedListener { _, destination, _ ->
            val dest = try {
                resources.getResourceName(destination.id)
            } catch (e: Resources.NotFoundException) {
                destination.id.toString()
            }
            Log.i(javaClass.simpleName, "navigated to $dest")
        }
        ServiceUtils.startService(NotificationService::class.java)
        ServiceUtils.bindService(
            NotificationService::class.java,
            connection,
            Context.BIND_AUTO_CREATE
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        ServiceUtils.unbindService(connection)
        ServiceUtils.stopService(NotificationService::class.java)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == RESULT_OK) {
            val viewModel = ViewModelProvider(
                this,
                EmployeeViewModelFactory()
            ).get(EmployeeViewModel::class.java)
            val list = ArrayList<Uri>()
            val bmp = data?.getParcelableExtra<Bitmap>("data")
            LogUtils.i("bitmap is $bmp")
            bmp?.let { viewModel.addBitmap(it) }
            data?.let {
                val imageNames = it.clipData ?: run {
                    it.data?.let { it1 -> list.add(it1) }
                    viewModel.addImages(list)
                    return
                }
                for (i in 0 until (imageNames.itemCount)) {
                    val item = imageNames.getItemAt(i)?.uri ?: continue
                    list.add(item)
                }
            }
            viewModel.addImages(list)
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent?.action == NEW_ORDER_NOTIFY_ACTION) {
            val data = intent.getBundleExtra(NEW_ORDER_NOTIFY)
            val response = data?.getString(NEW_ORDER_NOTIFY)
            val socketResponse = GsonUtils.fromJson(
                response,
                WebSocketResponse::class.java
            )
            val id = socketResponse.data.serviceOrderId
            newOrderListener?.invoke(id)
        }
    }

    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            _binder = service as NotificationService.NotificationBinder
            _binder?.getService()?.notifyListener = {
                ToastUtils.showLong("有新的订单派发给你哦")
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) = Unit
    }

    fun startWebSocket(employeeId: String) {
        LogUtils.i("=========== startWebSocket")
        _binder?.startWebSocket(employeeId)
    }

    fun setOrderListener(listener: (String?) -> Unit) {
        _binder?.getService()?.notifyListener = listener
    }

    fun setNewOrderListener(listener: (String) -> Unit) {
        newOrderListener = listener
    }

    private fun saveBitmap(bm: Bitmap?): Uri? {
        //新建文件夹用于存放裁剪后的图片
        val tmpDir = File(filesDir.absolutePath + "/temp")
        if (!tmpDir.exists()) {
            tmpDir.mkdir()
        }

        //新建文件存储裁剪后的图片
        val img = File(tmpDir.absolutePath.toString() + "/avator.png")
        val fos = FileOutputStream(img)
        return fos.use {
            //打开文件输出流
            //将bitmap压缩后写入输出流(参数依次为图片格式、图片质量和输出流)
            bm?.compress(Bitmap.CompressFormat.PNG, 85, it)
            //刷新输出流
//            fos.flush()
            //关闭输出流
//            fos.close()
            //返回File类型的Uri
            Uri.fromFile(img)
        }
    }
}